package com.stylefeng.guns.modular.system.task;

import java.net.URI;
import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.util.HttpClientUtil;
import com.stylefeng.guns.modular.system.constants.ImportContants;

@Service
public class GgMoneyTotalImportTask{

	private Logger log = LoggerFactory.getLogger(GgMoneyTotalImportTask.class);
	
	private static final HttpClientUtil clientUtil = new HttpClientUtil();
	
	public void execute(boolean isHoliday) {
		String url = ImportContants.getGeguMoneyTotal(1);
		HttpGet httpGet = HttpClientUtil.getGetRequest();
		try {
			URL http = new URL(url);
			URI uri = new URI(http.getProtocol(), http.getHost(), http.getPath(), http.getQuery(), null);
			httpGet.setURI(uri);
			String json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
			JSONObject jsonObj = JSON.parseObject(StringUtils.substringAfter(json, "="));
			int pages = jsonObj.getIntValue("pages");
			parseData(jsonObj.getString("data"));
			for(int i= 2; i <=pages ; i++){
				url = ImportContants.getGeguMoneyTotal(i);
				http = new URL(url);
				uri = new URI(http.getProtocol(), http.getHost(), http.getPath(), http.getQuery(), null);
				httpGet.setURI(uri);
				json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
				jsonObj = JSON.parseObject(StringUtils.substringAfter(json, "="));
				parseData(jsonObj.getString("data"));
			}
		} catch (Exception e) {
			log.error("get gegu money total is error!" + e);
		}finally{
			httpGet.abort();
		}
	}

	private void parseData(String json) {
		String[] ggzjs = StringUtils.substringsBetween(json, "\"", "\"");
		for(String ggzj : ggzjs){
			try{
				if(StringUtils.isNotEmpty(ggzj)){
					System.out.println(ggzj);
				}
			}catch(Exception e){
				log.error("parse error!" ,e);
			}
		}
	}
}
